<template>
	<!-- 编辑弹出框 -->
	<el-dialog :title="dialogTitle" v-model="dialogVisible" align-center width="80%">
		<el-form ref="theFormRef" :model="dataForm" label-width="100px">
			<el-form-item label="序号"><el-input v-model="dataForm.sort"></el-input></el-form-item>
			<el-form-item label="轮播图片"><el-input v-model="dataForm.img"></el-input></el-form-item>
			
			<el-form-item label="商品id"><goods-select v-model="dataForm.goodsId"></goods-select></el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button size="medium" @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" size="medium" @click="handleSubmit">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup>
import * as HomeAPI from '@/api/home.js';
import GoodsSelect from './GoodsSelect.vue';

import { ref, computed, defineEmits, nextTick ,defineExpose } from 'vue';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false); //是否显示
const dataForm = ref({ id: 0 }); //表单

//弹框标题
const dialogTitle = computed(() => {
	return !dataForm.value.id ? '新增' : '编辑';
});

//声明一个模板中DOM元素的引用, 必须和模板里的 ref 同名
const theFormRef = ref(null);
const emit = defineEmits(['refreshDataList']);

const init = async id => {
	dataForm.value.id = id || 0;
	dialogVisible.value = true;
	await nextTick();
	theFormRef.value.resetFields();
	if (id) {
		//是编辑
		let result = await HomeAPI.getDetailById(id);
		dataForm.value = result.data; //看接口文档，知道data是对应的用户对象
	} else {
		//是新增
		setDataFormToDefault();
	}
};

const setDataFormToDefault = () => {
	//初始默认值
	let defaultForm = {};
	defaultForm.id = 0;
	defaultForm.typeId = 1; // 是轮播
	defaultForm.img = '';
	defaultForm.goodsId = null;
	defaultForm.sort = 0;
	dataForm.value = Object.assign({}, defaultForm);
};

//提交确认
const handleSubmit = () => {
	theFormRef.value.validate(async valid => {
		if (valid) {
			await HomeAPI.save(dataForm.value);
			ElMessage.success(`保存成功`);
			dialogVisible.value = false;
			emit('refreshDataList'); //重新刷新列表数据
		}
	});
};

//暴露接口方法
defineExpose({
	init
});
</script>

<style scoped></style>
